<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="back"></i>
      <p>在线支付</p>
    </header>
    <!-- 订单信息部分 -->
    <h3>订单信息：</h3>
    <div class="order-info">
      <p>
        {{ orders.business.businessName }}
        <i class="fa fa-caret-down" @click="detailetShow"></i>
      </p>
      <p>&#165;{{ orders.orderTotal }}</p>
    </div>
    <!-- 订单明细部分 -->
    <ul class="order-detailet" v-show="isShowDetailet">
      <li v-for="item in orders.list" :key="item.id">
        <p>{{ item.food.foodName }} x {{ item.quantity }}</p>
        <p>&#165;{{ item.food.foodPrice * item.quantity }}</p>
      </li>
      <li>
        <p>配送费</p>
        <p>&#165;{{ orders.business.deliveryPrice }}</p>
      </li>
      <li>
        <p>积分</p>
        <p>-&#165;{{ reduction }}</p>
      </li>
      <li v-if="walletPayment > 0">
        <p>钱包余额支付</p>
        <p>-&#165;{{ walletPayment }}</p>
      </li>
    </ul>
    <!-- 钱包余额部分 -->
    <div class="wallet-info" v-if="walletBalance !== null && orders.business.businessName !== '充值'">
      <p>可用钱包余额: &#165;{{ walletBalance }}</p>
      <div class="wallet-input">
        <label for="wallet-payment">使用钱包余额支付:</label>
        <input 
          type="number" 
          id="wallet-payment" 
          v-model.number="walletPayment" 
          :max="availableWalletPayment" 
          min="0" 
          step="0.01"
          placeholder="0.00"
        >
      </div>
    </div>
    <!-- 支付方式部分 -->
    <ul class="payment-type">
      <li @click="selectPaymentMethod('alipay')">
        <img src="../assets/img/alipay.png">
        <i class="fa fa-check-circle" v-if="selectedPaymentMethod === 'alipay'"></i>
      </li>
      <li @click="selectPaymentMethod('wechat')">
        <img src="../assets/img/wechat.png">
        <i class="fa fa-check-circle" v-if="selectedPaymentMethod === 'wechat'"></i>
      </li>
    </ul>
    <div class="payment-button">
      <button :style="{ backgroundColor: isPayed ? 'gray' : '#38CA73' }" @click="pay">确认支付</button>
    </div>
    <h2 v-show="paySuccess" style="color: #0097FF; text-align: center;">
      支付成功！
    </h2>
    <!-- 底部菜单部分 -->
    <Footer />
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import Footer from '../components/Footer.vue';

export default {
  name: 'Payment',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const orderId = ref(route.query.orderId);
    const userId = ref(route.query.userId);
    const reduction = ref(route.query.reduction);
    const orders = ref({ business: {} });
    const isShowDetailet = ref(false);
    const paySuccess = ref(false);
    const isPayed = ref(false);
    const selectedPaymentMethod = ref('alipay'); // 默认选中支付宝
    const walletBalance = ref(null);
    const walletPayment = ref(0.00);

    onMounted(() => {
      fetchOrdersById();
      fetchWalletBalance();
      // 阻止后退
      history.pushState(null, null, document.URL);
      window.onpopstate = () => {
        router.push('/index');
      };
    });

    onUnmounted(() => {
      window.onpopstate = null;
    });

    const fetchOrdersById = async () => {
      try {
        const url = `OrdersController/getOrdersById/${orderId.value}`;
        const response = await axios.get(url, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        orders.value = response.data.result;
      } catch (error) {
        console.error(error);
      }
    };

    const fetchWalletBalance = async () => {
      try {
        const url = `WalletController/balance/${userId.value}`;
        const response = await axios.get(url, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        walletBalance.value = response.data.result;
      } catch (error) {
        console.error('获取钱包余额失败:', error);
        walletBalance.value = 0.00;
      }
    };

    const detailetShow = () => {
      isShowDetailet.value = !isShowDetailet.value;
    };

    const selectPaymentMethod = (method) => {
      selectedPaymentMethod.value = method;
    };

    const pay = async () => {
      if (!selectedPaymentMethod.value) {
        alert('请选择支付方式');
        return;
      }
	  // 判断是否超出钱包余额
	    if (walletPayment.value > walletBalance.value) {
	      alert('输入的金额不能超过钱包余额！');
	      return;
	    }

      try {
        // 判断是否为充值操作（根据 businessName 判断）
        const isRecharge = orders.value.business.businessName === '充值';

        if (isRecharge) {
          // 充值逻辑
          const response = await axios.post(`/WalletController/deposit/${userId.value}/${orders.value.orderTotal}`, {}, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          });

          if (response.data.result === "充值成功") {
            paySuccess.value = true;
            isPayed.value = true;
            setTimeout(() => {
              router.push('/wallet');
            }, 500);
          } else {
            alert('充值失败！');
          }
        } else {
          // 订单支付逻辑
          const response = await axios.post(`OrdersController/payOrdersById/${orderId.value}`, {}, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          });

          if (response.data.result > 0) {
            // 扣除钱包余额
            if (walletPayment.value > 0) {
              await axios.post(`/WalletController/deposit/${userId.value}/${-walletPayment.value}`, {}, {
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                }
              });
            }
			// 给商家充值
			        const businessId = orders.value.business.businessId; // 获取商家ID
			        const orderTotal = orders.value.orderTotal; // 获取订单总金额
			        await axios.post(`/WalletController/deposit/${businessId}/${orderTotal}`, {}, {
			          headers: {
			            'Content-Type': 'application/x-www-form-urlencoded'
			          }
			        });


            paySuccess.value = true;
            isPayed.value = true;

            // 调用后端接口扣除积分
            try {
              let deductpointNum = parseInt(reduction.value * 10);
              let deductUrl = `PointsController/use/${userId.value}/${deductpointNum}`;
              const deductPointsResponse = await axios.post(deductUrl, {}, {
                headers: {
                  'Content-Type': 'application/json'
                }
              });
              if (deductPointsResponse.data.result === 'Points used successfully') {
                // 积分扣除成功，导航到订单列表或其他页面
                router.push('/orderList');
              }
            } catch (error) {
              console.error('扣除积分错误:', error);
              alert('扣除积分时发生错误');
            }

            // 调用后端接口积累积分
            try {
              let addpointNum = parseInt(orders.value.orderTotal / 10);
              let addUrl = `PointsController/add/${userId.value}/${addpointNum}`;
              const addPointsResponse = await axios.post(addUrl, {}, {
                headers: {
                  'Content-Type': 'application/json'
                }
              });
              if (addPointsResponse.data.result === 'Points added successfully') {
                // 积分添加成功，导航到订单列表或其他页面
                router.push('/orderList');
              }
            } catch (error) {
              console.error('添加积分错误:', error);
              alert('添加积分时发生错误');
            }

            setTimeout(() => {
              router.push('/orderList');
            }, 500);
          } else {
            alert('支付失败！');
          }
        }
      } catch (error) {
        console.error('支付错误:', error);
        alert('支付时发生错误');
      }
    };

    const back = () => {
      router.back();
    };

    // 计算可用钱包支付金额（不能超过余额和订单总额）
    const availableWalletPayment = computed(() => {
      if (!walletBalance.value || !orders.value.orderTotal) return 0.00;
      return Math.min(walletBalance.value, orders.value.orderTotal);
    });

    return {
      orders,
      isShowDetailet,
      detailetShow,
      pay,
      isPayed,
      paySuccess,
      selectedPaymentMethod,
      selectPaymentMethod,
      back,
      walletBalance,
      walletPayment,
      availableWalletPayment
    };
  },
  components: {
    Footer
  }
};
</script>


<style scoped>
	.wallet-info {
	  background-color: #f8f9fa;
	  padding: 15px;
	  border-radius: 8px;
	  margin: 15px 0;
	}
	
	.wallet-input {
	  margin-top: 10px;
	}
	
	.wallet-input label {
	  display: block;
	  margin-bottom: 5px;
	  font-weight: bold;
	}
	
	.wallet-input input {
	  width: 100%;
	  padding: 8px;
	  border: 1px solid #ddd;
	  border-radius: 4px;
	}
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    height: 100%;
  }

  /****************** header部分 ******************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #01B0F2;
    font-size: 4.8vw;
    color: #fff;

    z-index: 10;

    display: flex;
    justify-content: flex-start;
    align-items: center;

    position: fixed;
    left: 0;
    top: 0;
  }

  .wrapper header i {
    margin: 0vw 0vw 0vw 3vw;
    font-size: 6vw;
    user-select: none;
    cursor: pointer;
  }

  .wrapper header p {
    margin: 0vw 0vw 0vw 33.5vw;
  }

  /****************** 订单信息部分 ******************/
  .wrapper h3 {
    margin-top: 12vw;
    box-sizing: border-box;
    padding: 4vw 4vw 0;
    font-size: 4vw;
    font-weight: 300;
    color: #999;
  }

  .wrapper .order-info {
    box-sizing: border-box;
    padding: 4vw;
    font-size: 4vw;
    color: #666;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .order-info p:last-child {
    color: orangered;
  }

  /****************** 订单明细部分 ******************/
  .wrapper .order-detailet {
    width: 100%;
  }

  .wrapper .order-detailet li {
    width: 100%;
    box-sizing: border-box;
    padding: 1vw 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .order-detailet li p {
    font-size: 3vw;
    color: #666;
  }

  /****************** 支付方式部分 ******************/
  .wrapper .payment-type {
    width: 100%;
  }

  .wrapper .payment-type li {
    width: 100%;
    box-sizing: border-box;
    padding: 4vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .wrapper .payment-type li img {
    width: 33vw;
    height: 8.9vw;
  }

  .wrapper .payment-type li .fa-check-circle {
    font-size: 5vw;
    color: #38CA73;
  }

  .wrapper .payment-button {
    width: 100%;
    box-sizing: border-box;
    padding: 4vw;
  }

  .wrapper .payment-button button {
    width: 100%;
    height: 10vw;
    border: none;
    font-size: 3vw;
    /*去掉外轮廓线*/
    outline: none;
	border-radius: 4px;
	color: #fff;
}
</style>

